package com.example.hanchen.yongkanggy.utils;

import android.annotation.SuppressLint;
import android.util.Log;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/*字典排序*/
public class QueryStringSorter {
    @SuppressLint("NewApi")
    public static String sortQueryString(String queryString) {

        // 分割查询字符串为键值对数组
        String[] pairs = queryString.split("&");
        // 对键值对数组进行字典排序
        Arrays.sort(pairs, (pair1, pair2) -> {
            String key1 = pair1.split("=")[0];
            String key2 = pair2.split("=")[0];
            Log.i("FEFEFOKEF", "pairs" + pairs + " key1 " + key1 + " key2 " + key2);
            return key1.compareTo(key2);
        });
        // 将排序后的键值对重新组合成查询字符串
        return String.join("&", pairs);
    }


    /*去除无参的数据*/
    public static String cleanEmptyParams(String queryString) {
        // 去除开头的问号（如果有的话）
        if (queryString.startsWith("?")) {
            queryString = queryString.substring(1);
        }

        // 将查询字符串分割为键值对
        String[] pairs = queryString.split("&");
        Map<String, String> params = new HashMap<>();
        for (String pair : pairs) {
            String[] keyValue = pair.split("=", 2);
            if (keyValue.length == 2 && !keyValue[1].isEmpty()) {
                // 只添加值不为空的键值对
                params.put(keyValue[0], keyValue[1]);
            }
        }

        // 将处理后的键值对重新组合为查询字符串
        StringBuilder cleanedStringBuilder = new StringBuilder();
        boolean firstParam = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (!firstParam) {
                cleanedStringBuilder.append("&");
            }
            cleanedStringBuilder.append(entry.getKey()).append("=").append(entry.getValue());//TODO UTF-8的数据 需要转换
            firstParam = false;
        }

        String data = sortQueryString(cleanedStringBuilder.toString());
        return data;
    }
}
